package chan.project.template;

import chan.project.common.ErrorCode;
import chan.project.exception.BusinessException;
import chan.project.exception.ThrowUtils;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
@Component
public class UrlPictureUpload extends PictureUploadTemplate{
    @Override
    public void validFile(Object inputSource) {
        String url = (String) inputSource;
        ThrowUtils.throwIf(StringUtils.isBlank(url), ErrorCode.PARAMS_ERROR,"url为空");
        //1.验证url的正确性
        try {
            new URL(url);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2.验证url协议
        ThrowUtils.throwIf(!url.startsWith("http://") && !url.startsWith("https://")
                ,ErrorCode.PARAMS_ERROR,"url协议错误");
        //3.验证文件是否存在
        try (HttpResponse response = HttpUtil.createRequest(Method.HEAD, url).execute()) {
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            String contentType = response.header("Content-Type");
            if (StringUtils.isNotBlank(contentType)) {
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/png", "image/webp", "image/jpeg", "image/jpg");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()), ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
            //4.验证文件大小
            String contentLengthStr = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                try {
                    long contentLength = Long.parseLong(contentLengthStr);
                    final long TWO_MB = 2 * 1024 * 1024L;
                    ThrowUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过2MB");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小超限");
                }
            }
        }
    }

    @Override
    public String getOriginalFilename(Object inputSource) {
        String url = (String) inputSource;
        return FileUtil.mainName(url);
    }

    @Override
    public void saveFile(Object inputSource, File file) throws IOException {
        String url = (String) inputSource;
        HttpUtil.downloadFile(url,file);
    }
}
